package permission

import (
	"context"
	"fmt"
	"github.com/samber/lo"
	"private-domain-overseas-service/admin/business/api/internal/repository/permission"
	"private-domain-overseas-service/admin/business/api/internal/svc"
	"private-domain-overseas-service/admin/business/api/internal/types"
	"private-domain-overseas-service/pkg/xerr"
	"private-domain-overseas-service/tools/ent"
	"private-domain-overseas-service/tools/ent/adminrole"
	"private-domain-overseas-service/tools/ent/predicate"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type AdminRoleListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// NewAdminRoleListLogic - 后台角色查询接口
func NewAdminRoleListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminRoleListLogic {
	return &AdminRoleListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

// AdminRoleList - 后台角色查询接口
func (l *AdminRoleListLogic) AdminRoleList(req *types.AdminRoleListRequest) (resp *types.AdminRoleListResponse, err error) {
	adminRoleDAO := permission.NewAdminRoleDao(l.ctx, l.svcCtx)

	// 查询用户角色列表
	conditions := make([]predicate.AdminRole, 0)
	if req.AdminRoleName != "" {
		conditions = append(conditions, adminrole.AdminRoleNameContains(req.AdminRoleName))
	}
	if req.AdminRoleDesc != "" {
		conditions = append(conditions, adminrole.AdminRoleDescContains(req.AdminRoleDesc))
	}
	adminRoles, total, err := adminRoleDAO.AdminRoleConditionsPageAll(req, conditions)
	if err != nil {
		return nil, xerr.ErrCodeMsg(xerr.ServerOperationExceptionError, fmt.Sprintf("查询用户角色列表失败：%v", err.Error()))
	}

	// 组装数据
	list := lo.Map(adminRoles, func(item *ent.AdminRole, _ int) *types.AdminRoleInfo {
		return &types.AdminRoleInfo{
			AdminRoleId:        int64(item.ID),
			AdminRoleName:      item.AdminRoleName,
			AdminRoleDesc:      item.AdminRoleDesc,
			AdminRoleType:      item.AdminRoleType,
			AdminRoleRouterIds: item.AdminRoleRouterIds,
			CreateAt:           item.CreateAt.Format(time.DateTime),
			UpdateAt:           item.UpdateAt.Format(time.DateTime),
		}
	})

	// 返回数据
	return &types.AdminRoleListResponse{
		Page: &types.PageResponse{
			Total:           int64(total),
			PageSize:        int64(len(list)),
			RequestPageSize: req.PageSize,
			Current:         req.Current,
		},
		List: list,
	}, nil
}
